<?php
/**
 * ERP 系统基类
 */
namespace request\erp;

use request\Request;
use request\RequestException;

class BaseRequest extends Request {

    protected $method = 'post';
    protected $baseApi = 'http://mall.micromall.emedo.com.cn';
    protected $action = '';

    protected $config = [
        'pwd_key' => 'shUiyUAnguoji123',
        'pwd_iv' => 'sY273281',
        'md5_key' => 'shUiyUAnguoji123',
    ];

    public function __construct()
    {
        $this->setUrl($this->baseApi.$this->action);
        $this->setRequestOptions([
            'headers' => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
            'verify'=>false
        ]);
    }


    protected function getSign($params) {
        if(isset($params['signature'])) unset($params['signature']);

        ksort($params);
        $signData = [];
        foreach ($params as $key => $val) {
            $signData[] = $key . '=' . $val;
        }

        return  md5(implode('&', $signData).$this->config['md5_key']);
    }


    /**
     * @return mixed
     */
    public function getParams()
    {
        $params = $this->requestTransfer($this->params);
        $params['version'] = '1.0';
        $params['signMethod'] = '01';
        $params['signature'] = $this->getSign($params);
        return $params;
    }

    /**
     * @return mixed
     */
    public function getPost()
    {
        $params = $this->requestTransfer($this->post ?: $this->params);
        $params['signature'] = $this->getSign($params);
        return $params;
    }

    // 响应验证
    public function checkResponse($response)
    {
        if($response['respCode'] != '00') {
            throw new RequestException($response['respMsg']);
        }
    }

    // 获取响应
    public function getResponse()
    {
        return parent::getResponse(); // TODO: Change the autogenerated stub
    }

    // 重构 响应
    public function setResponse($response)
    {
        parse_str($response, $this->response);
        $this->checkResponse($this->response);
    }

    /**
     *加密
     * @param <type> $value
     * @return <type>
     */
    protected function encrypt($value)
    {
        $key = $this->config['pwd_key'];

        // 对接java，服务商做的AES加密通过SHA1PRNG算法（只要password一样，每次生成的数组都是一样的），Java的加密源码翻译php如下：
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        // openssl_encrypt 加密不同Mcrypt，对秘钥长度要求，超出16加密结果不变
        $data = openssl_encrypt($value, 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        $data = strtoupper(bin2hex($data));
        return $data;
    }

    /**
     * @param string $string 需要解密的字符串
     * @param string $key 密钥
     * @return string
     */
    public function decrypt($string)
    {
        $key = $this->config['pwd_key'];
        // 对接java，服务商做的AES加密通过SHA1PRNG算法（只要password一样，每次生成的数组都是一样的），Java的加密源码翻译php如下：
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $decrypted = openssl_decrypt(hex2bin($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
        return $decrypted;
    }
}